const enterpriseVue = new Vue({
    el: '#app',
    data() {
        return {
            pickerOptions: pickerOptions,
            rules: {

            },
            dialogVisible: false,//导入
            form: {//销售订单
                Sales_Order_SerialNumber: "",
                Store_SerialNumber: '',
                Sales_Address: '',
                Sales_Type: '',
                Sales_Contacts: '',
                Sales_Phone: '',
                Sales_Message: '',
                Sales_Date: '',
                Open_ID: '',
                Sales_Amount: '',
                Collection_Amount: '0',
                Delivery_Amount: '0',
                Sales_ID: '',
                Receive_Type: '0',
                Refund_Type: '0',
                Order_Type: '0',
                User_Cancellation: '0',
                LogisticsNumbers: '',
                Logistics_Date: '',
                Dealer_SerialNumber: '',
                App_ID: '',
                Enterprise_Info_SerialNumber: $.cookie("enterprise"),
                Children: {
                    sales_order_detail: [{     //销售订单明细
                        Sales_Order_Detail_SerialNumber: "",
                        Sales_Order_SerialNumber: '',
                        Sales_Unit_Price_Stock_SerialNumber: '',
                        Article_SerialNumber: '',
                        Article_Specifications_SerialNumber: '',
                        Sign: '有货货主',
                        Unit_Price: '',
                        Sales_Unit_Price: '',
                        Quantity: '',
                        Amount: '',
                        Receive_Type: '0',
                        Refund_Type: '0',
                        Order_Type: '0',
                        Supplier_SerialNumber: '',
                        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
                        specs: []
                    }]
                }
            },
            loading: false,
            dealer: [],//存放经销商数组
            article: [],//存放商品
            store: [],//店铺
            city: [],//地址字典
            Address: [],//地址
            AddressDetail: '',//详细地址
            tableData: [],//导入
            formData: {
                page: 1,
                limit: 10
            },
            OrderType:0
        }
    },
    mounted() {
        this.OrderType = sessionStorage.getItem("OrderType")
        console.log(this.OrderType );
        this.getData()
    },
    methods: {
        getData() {
            let _this = this;
            $.ajax({
                url: absolutepath() + "js/city.json",
                type: "GET",
                success: function (data) {
                    _this.city = data
                },
                dataType: "json"
            })
            $.ajax({
                url: DomainName + '/getSalesArticleAction?token=' + $.cookie("token"),
                type: 'POST',
                data: {
                    Enterprise_Info_SerialNumber: $.cookie("enterprise")
                },
                success: function (res) {
                    _this.article = res.Data
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
            $.ajax({
                type: 'POST',
                url: DomainName + "/getInquiryAction?token=" + $.cookie('token'),
                data: {
                    Data: "dealer_info",
                },
                success: function (res) {
                    _this.dealer = res;
                },
                complete: function (XMLHttpRequest) {
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                },
                dataType: "json"
            });
            $.ajax({
                type: 'POST',
                url: DomainName + "/getInquiryAction?token=" + $.cookie('token'),
                data: {
                    Data: "store_info",
                },
                success: function (res) {
                    _this.store = res;
                },
                complete: function (XMLHttpRequest) {
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                },
                dataType: "json"
            });
        },
        handleAddress() {//选择地址
            this.AddressDetail = '';
        },
        ChangeRadio(e, index) {//无货/有货切换
            this.form.Children.sales_order_detail[index].Article_SerialNumber = ''
            this.form.Children.sales_order_detail[index].Article_Specifications_SerialNumber = ''
            this.form.Children.sales_order_detail[index].Unit_Price = ''
            this.form.Children.sales_order_detail[index].Sales_Unit_Price = ''
            this.form.Children.sales_order_detail[index].specs = []
        },
        Change_Unit_Price(index, item) {//设置价格
            item.Article_Specifications_SerialNumber = ''
            $.ajax({
                type: 'POST',
                url: DomainName + "/SpecificationsIDAction?token=" + $.cookie("token"),
                data: {
                    Article_SerialNumber: item.Article_SerialNumber,
                },
                success: function (res) {
                    item.specs = res
                },
                complete: function (XMLHttpRequest) {
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                },
                dataType: "json"
            });
        },
        Change_Specifications_Name(index, item) {
            let obj = item.specs.filter(i => i.Article_Specifications_SerialNumber == item.Article_Specifications_SerialNumber)[0]
            item.Unit_Price = obj.Unit_Price
            item.Sales_Unit_Price = obj.Unit_Price
            this.count(item);
        },
        count(item) {//计算
            item.Amount = accMul(item.Sales_Unit_Price, item.Quantity)
            this.form.Sales_Amount = 0;
            this.form.Children.sales_order_detail.forEach(ite => {
                if (ite.Sales_Unit_Price) {
                    this.form.Sales_Amount = accAdd(this.form.Sales_Amount, ite.Amount)
                }
            })
        },
        add_sales_order_detail() {//添加
            this.form.Children.sales_order_detail.push({     //销售订单明细
                Sales_Order_Detail_SerialNumber: "",
                Sales_Order_SerialNumber: '',
                Sales_Unit_Price_Stock_SerialNumber: '',
                Article_SerialNumber: '',
                Article_Specifications_SerialNumber: '',
                Sign: '有货货主',
                Unit_Price: '',
                Sales_Unit_Price: '',
                Quantity: '',
                Amount: '',
                Receive_Type: '0',
                Refund_Type: '0',
                Order_Type: '0',
                Supplier_SerialNumber: '',
                Enterprise_Info_SerialNumber: $.cookie("enterprise"),
                specs: []
            })
        },
        remove_sales_order_detail() {//删除
            if (this.form.Children.sales_order_detail.length > 1) {
                this.form.Children.sales_order_detail.pop()
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        tableCellStyle({ row, column, rowIndex, columnIndex }) {
            if (!row.Abnormal) return { backgroundColor: '#E6A23C' }

        },
        handleSizeChange(val) {
            this.formData.page = 1;
            this.formData.limit = val;
        },
        handleCurrentChange(val) {
            this.formData.page = val;
        },
        //获取外企也商品主键
        submitForm(formName) {
            let _this = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    _this.loading = true
                    //1.将主键外键填写完毕
                    _this.form.Sales_Address = _this.Address.join('/') + '/' + _this.AddressDetail
                    _this.form.Children.sales_order_detail.forEach((item, index) => {
                        item.Sales_Order_SerialNumber = _this.form.Sales_Order_SerialNumber
                        item.Sales_Order_Detail_SerialNumber = _this.form.Sales_Order_SerialNumber + '_' + addZero(index + 1, 3)
                    })
                    console.log(_this.form);
                    $.ajax({
                        url: DomainName + '/getAddAction?token=' + $.cookie("token"),
                        type: 'POST',
                        data: {
                            Data: JSON.stringify({
                                sales_order: [_this.form]
                            }),
                        },
                        success: function (res) {
                            if (res.Status === 'success') {
                                _this.$message.success("操作成功")
                                window.history.go(-1);
                            } else {
                                _this.$message.error("操作失败，请稍后再试")
                            }
                        },
                        error: function () {
                            _this.$message.error("操作失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            _this.loading = false
                            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                            }
                        }
                    })
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        /**
         * 导入开始
         */
        onExcel() {
            this.dialogVisible = true
        },
        subFile() {
            console.log($.cookie("token"))
            let _this = this
            var file = document.getElementById('inputfile').files[0]; // 获取选择的文件
            if (!file) return;
            var reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
                str.forEach(item => {
                    let obj = _this.isArticle(item['规格编码']);
                    let Dealer = _this.isDealer(item['经销商'])
                    let Abnormal = [obj.abnormal, Dealer.abnormal]
                    _this.tableData.push({
                        Dealer_Order_SerialNumber: item['订单号'],
                        Sales_Contacts: item['收货人'],
                        Sales_Phone: item['手机号码'],
                        Sales_Address: item['收货地址'].replaceAll(' ', '/'),
                        Specifications_Name: Object.keys(obj.article).length != 0 ? obj.article.Article_Name : '异常数据(' + item['商品规格名称'] + ')',
                        Gfbm: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Article_SerialNumber : '异常数据(' + item['规格编码'] + ')',
                        Quantity: item['发货数量'],
                        Sales_Message: item['用户备注'],
                        Amount: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Amount * item['发货数量'] : '',
                        Sales_Amount: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Amount * item['发货数量'] : '',
                        Collection_Amount: '0',
                        Dealer_SerialNumber: Dealer.Dealer_SerialNumber,
                        Dealer_Name: item['经销商'],
                        Article_Name: Object.keys(obj.article).length != 0 ? obj.article.Article_Name : '异常数据(' + item['商品名称'] + ')',
                        Article_SerialNumber: Object.keys(obj.article).length != 0 ? obj.article.Article_SerialNumber : '',
                        Article_Specifications_SerialNumber: Object.keys(obj.article).length != 0 ? obj.article.Article_Specifications_SerialNumber : '',
                        Sales_Unit_Price: Object.keys(obj.article).length != 0 ? obj.article.Dealer_Amount : '',
                        Abnormal: !Abnormal.some(item => item == false),
                    })
                })
            }
            console.log(_this.form2);
        },
        isArticle(str) {
            if (this.article.some(item => item.Dealer_Article_SerialNumber == str)) {
                return { article: this.article.filter(item => item.Dealer_Article_SerialNumber == str)[0], abnormal: true }
            } else {
                return { article: {}, abnormal: false }
            }
        },
        isDealer(str) {
            if (this.dealer.some(item => item.Dealer_Name == str)) {
                return { Dealer_SerialNumber: this.dealer.filter(item => item.Dealer_Name == str)[0].Dealer_SerialNumber, abnormal: true }
            } else {
                return { Dealer_SerialNumber: '异常数据(' + str + ')', abnormal: false }
            }
        },
        beforeRemove() {
            this.fileList.pop()
            this.tableData = []
        },
        uploadDetails(file) {
            this.fileList.push({
                name: file.name,
                url: file.type
            })
            const _this = this
            var reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
                let arr = []
                console.log(json);
                json.forEach(item => {
                    arr.push({
                        Sales_Unit_Price_Detail_SerialNumber: "",
                        Sales_Unit_Price_SerialNumber: '',
                        Article_Specifications_SerialNumber: '',
                        Article_SerialNumber: '' + item['商品id'],
                        Article_Name: item['商品名称'],
                        Specifications_Name: item['商品规格'],
                        Unit_Price: item['原售价'],
                        Sales_Unit_Price: item['现售价'],
                        Sign: item['有/无货货主'],
                        Distribute: item['数量'],
                        Children: {
                            sales_unitprice_stock: []
                        }
                    })
                })

                _this.SalesUnitPriceImport({ Data: JSON.stringify(arr) }, (data) => {
                    _this.tableData = data
                    console.log(data);
                })
                // console.log(json);
                // let arr = []
                // json.forEach(item => {
                //   let Article = _this.isShop(item['品名'])
                //   // let Abnormal = [Article.abnormal]
                //   arr.push({
                //     Sales_Unit_Price_Detail_SerialNumber: "",
                //     Sales_Unit_Price_SerialNumber: '',
                //     Article_Specifications_SerialNumber: '',
                //     Article_SerialNumber: Article.Article_SerialNumber,
                //     Article_Name: item['商品名称'],
                //     Unit_Price: item['原售价'],
                //     Sales_Unit_Price: item['现售价'],
                //     Sign: item['有/无货货主'],
                //     Distribute: item['数量'],
                //     Abnormal: !Abnormal.some(item => item == false),
                //     Children: {
                //       sales_unitprice_stock: []
                //     }
                //   })
                // })
                // _this.tableData = arr
            }
        },
        SalesUnitPriceImport(data, callback) {
            this.loading = true
            $.ajax({
                url: `${DomainName}/getSalesUnitPriceImportAction?token=${$.cookie('token')}`,
                type: 'POST',
                data,
                success: (res) => {
                    callback(res.Data)
                },
                error: () => {
                    this.$message.error("操作失败，请稍后再试")
                },
                complete: (XMLHttpRequest) => {
                    this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })

        },
        submit(){
            let _this = this
            this.loading = true
            $.ajax({
              type: 'POST',
              data: {
                Data: JSON.stringify(_this.form2),
                token: $.cookie("token")
              },
              url: DomainName + '/setImportSalesOrder',
              success: function (res) {
                console.log(res);
                if (res.Status === 'success') {
                  _this.$message({
                    type: 'success',
                    message: res.hasOwnProperty("Cause")?res.Cause:'提交成功'
                  });
                  _this.dialogVisible1 = false
                  _this.getList(_this.form)
                } else {
                  _this.$message({
                    type: 'info',
                    message: res.hasOwnProperty("Cause")?res.Cause:'提交失败'
                  });
                }
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              dataType: "json"
            });
        }
    }
})